﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Processing;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Processing
{
    public class SeaveProcessingHandler : IRequestHandler<SeaveProcessingCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Processing_Table> _processingRepo;
        private readonly IMapper _mapper;

        public SeaveProcessingHandler(IBaseRepository<Processing_Table> processingRepo, IMapper mapper)
        {
            _processingRepo = processingRepo;
            _mapper = mapper;
        }
        /// <summary>
        /// 加工信息设置
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(SeaveProcessingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var processing =_processingRepo.GetAll().Where(p=>p.Batch_Id==request.Batch_Id && !p.IsDelete).FirstOrDefault();
            if (processing == null)
            {
                var model = _mapper.Map<Processing_Table>(request);
                model.CreateTime = DateTime.Now;
                model.Creater = "张三";
                model.UpdateTime = null;
                var res = _processingRepo.Add(model);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加失败";
                    return Task.FromResult(result);
                }

            }
            else
            {
                processing = _mapper.Map(request, processing);
                var res = _processingRepo.Update(processing);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改失败";
                    return Task.FromResult(result);
                }
            }
        }
    }
}
